<?php

namespace App\Services\IntegralGoods\Goods;

use App\Models\IntegralGoods\GoodsCategory;
use App\Services\Manage\ManageIndex;
use Illuminate\Support\Facades\DB;

/**
 * 商品 逻辑层
 * Class GoodsLogic
 * @package App\Services\Goods\Goods
 */
class GoodsCategoryLogic
{
    use \App\Services\Goods\Traits\BaseCheckCate;
    use \App\Services\Goods\Traits\UpdateCate;
    use \App\Services\User\Traits\addAppId;
    //修改商品分类
    public function editGoodsCate($data): array
    {
        return $this->_updateCate('\App\Services\IntegralGoods\Goods\GoodsCategoryLogic', 'App\Models\IntegralGoods\GoodsCategory', $data, 'dbCateList', 'dbOneCateInfo');
    }

    //添加商品分类
    public function addGoodsCate($data): array
    {
        $data['create_time'] = NOW;
        $data['update_time'] = NOW;
        $res = GoodsCategory::insert($data);
        return auto_return($res);
    }

    //内部db查询某分类信息
    public function dbOneCateInfo($data)
    {
        $_where[] = ['id','=',$data['id']];
        //$_where['status'] = isset($data['status']) ? $data['status'] : ['neq', -1];
        if(isset($data['status'])){
            $_where[]=['status','=',$data['status']];
        }else{
            $_where[]=['status','<>',-1];
        }

        return GoodsCategory::where($_where)
            ->first();
    }

    /*内部获取不包含公共分类的所有分类列表 查询结果可用于操作*/
    public function dbCateList($map = [])
    {

        isset($map['id']) && $_where[] = ['id','=',$map['id']];
        isset($map['pid']) && $_where[] = ['pid','=',$map['pid']];
        if (isset($map['app_id'])) {
            $isManageAppId = ManageIndex::Api()->_isManageAppId($map['app_id']);
            !$isManageAppId && $_where[] = ['app_id','=',$map['app_id']];
        }
        $_where[] = ['status','=',1];
        if(empty($map['action'])){
            $map['action'] = '';
        }
        if( $map['action'] == 'action'){
            unset($_where['pid']);
            return GoodsCategory::whereIn('pid',$map['pid'])->where($_where)
                ->get()->toArray();
        }else{
            return GoodsCategory::where($_where)
                ->get()->toArray();
        }

        //return GoodsCategory::where($_where)
//            ->get()->toArray();
    }

    /*内部获取包含公共分类的所有分类列表  仅查询不用于操作*/
    public function dbAllCateList($map = [])
    {
        isset($map['id']) && $_where[] = ['id', '=', $map['id']];
        isset($map['pid']) && $_where[] = ['pid', '=', $map['pid']];
        if (isset($map['status'])) {
            $_where[] = ['status', '=', $map['status']];
        } else {
            $_where[] = ['status', '<>', -1];
        }
        $que = GoodsCategory::where($_where);
        if (isset($map['app_id'])) {   //若卖家查看商品详情，则不传入app_id
            $manageAppId = ManageIndex::Api()->getAppId();
            $app_id = $map['app_id'];

            if ($manageAppId != $map['app_id']) {
                $que->Where(function ($query) use ($app_id) {
                    $query->where('app_id', $app_id)->orWhere(function ($query) use ($app_id) {
                        $query->whereRaw("FIND_IN_SET($app_id,`other_app_read`)");
                    })->orWhere('is_public', 1);
                });
            }
        }

        if (isset($map['limit']) && $map['limit']) {
            $que->limit($map['limit'])
                ->orderBy('order', 'ASC')
                ->orderBy('id', 'ASC');
        } else {
            $que->orderBy('order', 'ASC')
                ->orderBy('id', 'ASC');
        }
        $res = $que->get()->toArray();
        return $res;
    }

    /*前台检测该商品分类是否存在可读取 用于发布/编辑商品时的商品分类检测*/
    /*参数： app_id  id */
    public function checkReadCate($data): bool
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $manageAppId = ManageIndex::Api()->getAppId();
        $app_id = $data['app_id'];
        $res = GoodsCategory::where($_where);
        if ($manageAppId != $data['app_id']) {
            $res->Where(function ($query) use ($app_id) {
                $query->where('app_id', $app_id)->orWhere(function ($query) use ($app_id) {
                    $query->whereRaw("FIND_IN_SET($app_id,`other_app_read`)");
                })->orWhere('is_public', 1);
            });
        }
        $res->first();
        return $res ? true : false;
    }

    //后台获取某商品分类的详细信息
    public function oneCateInfo($data): array
    {
        $_where[] = ['id', '=', $data['id']];
        $_where[] = ['status', '<>', -1];

        $que = GoodsCategory::where($_where);

        $manageAppId = ManageIndex::Api()->getAppId();
        $app_id = $data['app_id'];
        if ($manageAppId != $data['app_id']) {
            $que->Where(function ($query) use ($app_id) {
                $query->where('app_id', $app_id)->orWhere(function ($query) use ($app_id) {
                    $query->whereRaw("FIND_IN_SET($app_id,`other_app_read`)");
                })->orWhere('is_public', 1);
            });
        }

        $res = $que->first();
        $res && $res = $res->toArray();
        return auto_return($res);
    }

    /*
        根据id数组 启用/禁用一个或多个分类
        父类被禁用，则其所有子类也被禁用，开启同理
    */
    public function changeCateStatus($data): array
    {

        $list = $this->dbCateList(['app_id' => $data['app_id']]);
        $saveData['status'] = $data['status'];

        foreach ($data['id'] as $k => $v) {
            $childId = child_ids($list, $v, 'id', 'pid', 'id');  //使用static数组 获取该分类下的所有子类
        }
        $data['id'] = array_merge($childId, $data['id']);
        $_where = ManageIndex::Api()->_addAppId($data['app_id']);

        if (!empty($_where)) {
            $res = GoodsCategory::whereIn('id', $data['id'])->where($_where)->update($saveData);
        } else {
            $res = GoodsCategory::whereIn('id', $data['id'])->update($saveData);
        }
        return auto_return($res);
    }

    //后台获取商品分类列表
    public function goodsCateList($data): array
    {
        return $this->_goodsCateList($data);
    }

    //获取商品分类列表
    public function _goodsCateList($data, bool $isFront = false): array
    {
        $where = ManageIndex::Api()->_addAppId($data['app_id']);
        $isFront && $_where[] = ['status', '=', 1];
        if (!empty($where)) {
            $list = $this->dbAllCateList($where);
        } else {
            $list = $this->dbAllCateList();
        }
        foreach ($list as $k => &$v) {
            $v['status_text'] = $v['status'] ? '正常' : '禁用';
        }
        $list = list_to_tree($list, 'id', 'pid', '_child', $data['id']);
        return auto_return($list);
    }
    //删除一个或多个商品分类
    public function delCate($data): array
    {
        $tem['pid'] = $data['id'];
        $tem['action'] = 'action';
        $map = ManageIndex::Api()->_addAppId($data['app_id']);
        if (!empty($map)) {
            $map=array_merge($tem,$map);
            $list = $this->dbCateList($map);
        } else {
            $list = $this->dbCateList($tem);
        }

        if(count($list) > 0){
            return auto_failure(null,'失败，存在子类'.$list[0]['name']);
        }

        $_where = ManageIndex::Api()->_addAppId($data['app_id']);
        $update['status'] = -1;
        $status['status']=[0,1];
        if(!empty($_where)) {

            $res = GoodsCategory::whereIn('id', $data['id'])->whereIn('status',$status['status'])->where($_where)->update($update);
        }else{
            $res=GoodsCategory::whereIn('id', $data['id'])->whereIn('status',$status['status'])->update($update);
        }
        return auto_return(1,'删除成功','删除失败');
    }


}